import * as Koa from 'koa';
import config from '../config';
import * as dateformat from 'dateformat';

export class APIError {
  constructor (public code: string, public message: string) {}
}

export const restify: Koa.Middleware = async(ctx, next) => {
  ctx.type = 'application/json';
  await next();
};

const requestDump = (request: Koa.Request) => {
  const reqInfo: any = {};
  reqInfo.method = request.method;
  reqInfo.url = request.url;
  reqInfo.header = request.header;
  reqInfo.body = request.body;
  return reqInfo;
};

export const APIErrorHandler: Koa.Middleware = async(ctx, next) => {
  try {
    await next();
  } catch (error) {
    ctx.status = 400;
    if (error instanceof APIError) {
      // 属于意料之中的情况，使用info级别
      console.info(`APIError: {code: '${error.code}', message: '${error.message}'}`);
      ctx.body = error;
    } else if (error instanceof Error) {
      console.error(`[${dateformat(new Date(), 'HH:MM:ss')}] Error: ${error.message}`);
      console.error(error.stack);
      // 进行request记录
      const reqInfo = requestDump(ctx.request);
      console.error(reqInfo);
      ctx.body = new APIError('internal: unknown_error', '服务器未知错误');
    }
  }
};
